package com.example.smart_city_0829.activity.commonweal;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.example.smart_city_0829.R;
import com.example.smart_city_0829.base.BaseActivity;
import com.example.smart_city_0829.base.CommonAdapter;
import com.example.smart_city_0829.entity.Base;
import com.example.smart_city_0829.entity.commonweal.CommonwealRecommendList;
import com.example.smart_city_0829.retrofit.NetCallBack;
import com.example.smart_city_0829.utils.Constant;
import com.example.smart_city_0829.view.MaxSizeLv;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;

public class CommonwealAllActivity extends BaseActivity {

    private EditText searchEt;
    private MaxSizeLv lv;
    private Button turnPage;

    private int dataCount = 0;

    private final int pageSize = 8;
    private int pageNum = 1;

    private ListAdapter listAdapter;
    private List<CommonwealRecommendList.RowsBean> data = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_commonweal_all;
    }

    @Override
    protected void initView() {
        searchEt = findViewById(R.id.search_et);
        lv = findViewById(R.id.lv);
        turnPage = findViewById(R.id.turn_page);
    }

    @Override
    protected void initData() {
        getListData();
    }

    @Override
    protected void initEvent() {
        searchEt.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                final Intent intent = new Intent(CommonwealAllActivity.this, CommonwealSearchActivity.class);
                intent.putExtra("key", searchEt.getText().toString());
                startActivity(intent);
                return true;
            }
            return false;
        });

        turnPage.setOnClickListener(v -> {
            if (dataCount == 0) {
                showToastShort("数据暂未加载，请稍后再试");
                return;
            }
            List<String> pageTag = new ArrayList<>();
            for (int i = 0; i < (dataCount / pageSize); i++) {
                pageTag.add("第" + (i + 1) + "页");
            }
            new AlertDialog.Builder(CommonwealAllActivity.this)
                    .setTitle("选择跳转页面")
                    .setSingleChoiceItems(
                            pageTag.toArray(new CharSequence[0]),
                            0,
                            (dialog, which) -> {
                                if (pageNum == which + 1) dialog.dismiss();
                                pageNum = which + 1;
                                getListData();
                                dialog.dismiss();
                            }
                    )
                    .create()
                    .show();
        });
    }

    @Override
    protected String getActionBarTitle() {
        return "公益列表";
    }

    private void getListData() {
        api.getWelfareList(pageSize, pageNum).enqueue(new NetCallBack<CommonwealRecommendList>() {
            @Override
            public void onResponse(@NonNull Call<CommonwealRecommendList> call, @NonNull Response<CommonwealRecommendList> response) {
                if (response.body() == null || response.body().getRows() == null) return;
                data = response.body().getRows();
                dataCount = response.body().getTotal();
                if (listAdapter == null) {
                    listAdapter = new ListAdapter(data, CommonwealAllActivity.this);
                    lv.setAdapter(listAdapter);
                } else {
                    listAdapter.resetData(data);
                    listAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    private void donateFor(int id) {
        final EditText dialogView = new EditText(CommonwealAllActivity.this);
        dialogView.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        new AlertDialog.Builder(this)
                .setTitle("输入捐款金额")
                .setView(dialogView)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        final HashMap<String, Object> params = new HashMap<>();
                        params.put("activityId", id);
                        params.put("donateMoney", dialogView.getText().toString());
                        RequestBody body = RequestBody.create(gson.toJson(params), MediaType.parse("application/json;contentType=utf-8"));
                        api.commonwealDonateFor(body).enqueue(new NetCallBack<Base>() {
                            @Override
                            public void onResponse(Call<Base> call, Response<Base> response) {
                                showToastShort("捐助成功");
                            }
                        });

                        dialog.dismiss();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    private final class ListAdapter extends CommonAdapter<CommonwealRecommendList.RowsBean, LVViewHolder> {

        public ListAdapter(List<CommonwealRecommendList.RowsBean> data, Context context) {
            super(data, context);
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void setData(CommonwealRecommendList.RowsBean data, int position, LVViewHolder viewHolder, View convertView, Context context) {
            Glide.with(CommonwealAllActivity.this)
                    .load(Constant.BASE_URL + data.getImgUrl())
                    .into(viewHolder.im);
            viewHolder.title.setText(data.getName());
            viewHolder.type.setText(String.valueOf(data.getName()));
            viewHolder.content.setText(data.getDescription());
            viewHolder.tag1.setText("捐赠人数：" + data.getDonateCount() + "\n" + "已筹善款：" + data.getMoneyTotal() + "\n发布组织：" + data.getAuthor());

            viewHolder.donate.setOnClickListener(v -> {
                //TODO
                donateFor(data.getId());
            });
        }

        @Override
        protected LVViewHolder getViewHolder() {
            return new LVViewHolder();
        }

        @Override
        protected void initView(LVViewHolder viewHolder, View convertView) {
            viewHolder.im = (ImageView) convertView.findViewById(R.id.im);
            viewHolder.title = (TextView) convertView.findViewById(R.id.title);
            viewHolder.type = (TextView) convertView.findViewById(R.id.type);
            viewHolder.content = (TextView) convertView.findViewById(R.id.content);
            viewHolder.tag1 = (TextView) convertView.findViewById(R.id.tag1);
            viewHolder.donate = (Button) convertView.findViewById(R.id.donate);
        }

        @Override
        protected int getItemLayoutResourceId() {
            return R.layout.commonweal_all_list_item;
        }
    }

    private static class LVViewHolder {
        ImageView im;
        TextView title;
        TextView type;
        TextView content;
        TextView tag1;
        Button donate;
    }
}